﻿using Digitalmes.Domain;
using Digitalmes.Infrastructure.Scada.Handlers;
using ThingsEdge.Contracts;
using ThingsEdge.Router.Forwarders;

namespace Digitalmes.Infrastructure.Scada.Forwarders;

/// <summary>
/// 请求消息（触发）处理。
/// </summary>
internal sealed class NativeRequestForwarderHandler(IServiceProvider serviceProvider, ILogger<NativeRequestForwarderHandler> logger) : IRequestForwarderHandler
{
    private static readonly Dictionary<string, Type> HandlerMap = new ()
    {
        { TagDefinition.PLC_Inbound_Sign, typeof(InboundHandler) },
        { TagDefinition.PLC_Archive_Sign, typeof(ArchiveHandler) },
        { TagDefinition.PLC_ScanKey_Sign, typeof(ScanKeyHandler) },
        { TagDefinition.PLC_ScanBatch_Sign, typeof(ScanBatchHandler) },
        { TagDefinition.PLC_Workstep_Sign, typeof(WorkstepHandler) },
    };

    public async Task<ResponseMessage> HandleAsync(RequestMessage message, CancellationToken cancellationToken = default)
    {
        ResponseMessage response = new()
        {
            Request = message,
        };

        ScadaResult result;
        var self = message.Self();

        if (HandlerMap.TryGetValue(self.TagName, out var typ))
        {
            var handler = (IScadaHandler)serviceProvider.GetRequiredService(typ);
            result = await handler.HandleAsync(message, cancellationToken);
        }
        else
        {
            logger.LogWarning("请求的标记名称 {TagName} 必须属于 {@Tags} 其中的一种。", self.TagName, HandlerMap.Keys);
            result = new() { State = (int)ErrorCode.E0002 };
        }

        response.State = result.State;
        response.CallbackItems = result.CallbackItems;
        return response;
    }
}
